package org.goobs.misc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Log {
	private static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
	
	public static final int NO_PRIORITY = Integer.MIN_VALUE;
	public static final int LOW_PRIORITY = 0;
	public static final int MEDIUM_PRIORITY = 1;
	public static final int HIGH_PRIORITY = 2;
	public static final int FORCE_PRIORITY = Integer.MAX_VALUE;
	
	public static final Log CONSOLE = new Log();
	
	protected static final Log UTILS = new Log();

	private boolean file = false;
	private FileWriter writer;
	private int minPriority;

	public Log(){
		this(LOW_PRIORITY);
	}
	
	public Log(int minPriority){
		this.minPriority = minPriority;
	}
	
	public Log(File logFile) throws IOException{
		this(logFile, LOW_PRIORITY);
	}

	public Log(File logFile, int minPriority) throws IOException {
		this.minPriority = minPriority;
		file = true;
		if (logFile.exists()) {
			if (!logFile.delete()) {
				throw new IOException("Could not delete old log file");
			}
		}
		if (!logFile.createNewFile()) {
			throw new IOException("Could not initialize log");
		}
		writer = new FileWriter(logFile);
	}

	protected boolean log(String msg, int priority) {
		if(priority < minPriority){
			return true;
		}
		if (file) {
			try {
				writer.write(msg + "\n");
				writer.flush();
			} catch (IOException e) {
				return false;
			}
			return true;
		} else {
			System.out.println(msg);
			return true;
		}
	}

	public LogThread branchThread(String prefix, int priority) {
		return new LogThread(prefix, priority, this);
	}

	public static String now() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		return sdf.format(cal.getTime());
	}
	
	public static String thread() {
		return "thread-" + Thread.currentThread().getId();
	}

}
